package com.njust.RateMyTray_backend.controller;

import com.njust.RateMyTray_backend.common.ForbiddenException;
import com.njust.RateMyTray_backend.common.Result;
import com.njust.RateMyTray_backend.config.JwtAuthInterceptor;
import com.njust.RateMyTray_backend.dto.DishCreateDTO;
import com.njust.RateMyTray_backend.dto.DishUpdateDTO;
import com.njust.RateMyTray_backend.dto.MerchantWindowUpdateDTO;
import com.njust.RateMyTray_backend.dto.ReplyCreateDTO;
import com.njust.RateMyTray_backend.entity.Dish;
import com.njust.RateMyTray_backend.entity.User;
import com.njust.RateMyTray_backend.service.CommentService;
import com.njust.RateMyTray_backend.service.DishService;
import com.njust.RateMyTray_backend.service.StatisticsService;
import com.njust.RateMyTray_backend.service.UserService;
import com.njust.RateMyTray_backend.service.WindowService;
import com.njust.RateMyTray_backend.vo.MerchantStatisticsVO;
import com.njust.RateMyTray_backend.vo.WindowDetailVO;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/merchant")
public class MerchantController {

    @Autowired
    private WindowService windowService;

    @Autowired
    private DishService dishService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CommentService commentService;

    @Autowired
    private StatisticsService statisticsService;

    private User getCurrentMerchant() {
        Claims claims = JwtAuthInterceptor.getCurrentUserClaims();
        String role = claims.get("role", String.class);
        if (!"merchant".equals(role)) {
            throw new ForbiddenException("只有商家才能操作此接口");
        }

        String currentUsername = claims.getSubject();
        User currentUser = userService.lambdaQuery().eq(User::getUsername, currentUsername).one();
        if (currentUser == null) {
            throw new ForbiddenException("无法获取当前用户信息，请重新登录");
        }
        return currentUser;
    }

    @GetMapping("/window")
    public ResponseEntity<Result<WindowDetailVO>> getMerchantWindow() {
        User currentUser = getCurrentMerchant();
        log.info("商家 {} 正在获取其管理的店铺信息", currentUser.getUsername());
        
        WindowDetailVO windowDetails = windowService.getMerchantFirstWindow(currentUser.getId());
        Result<WindowDetailVO> result = Result.success(200, "获取店铺信息成功", windowDetails);
        
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PutMapping("/windows/{windowId}")
    public ResponseEntity<Result<Void>> updateWindow(
            @PathVariable Long windowId,
            @RequestBody MerchantWindowUpdateDTO updateDTO) {
        
        User currentUser = getCurrentMerchant();
        log.info("商家 {} 正在更新窗口 {}", currentUser.getUsername(), windowId);
        windowService.updateWindowByMerchant(windowId, currentUser.getId(), updateDTO);

        return new ResponseEntity<>(Result.success(200, "窗口信息更新成功", null), HttpStatus.OK);
    }
    
    @PostMapping("/windows/{windowId}/dishes")
    public ResponseEntity<Result<Map<String, Long>>> createDish(
            @PathVariable Long windowId,
            @RequestBody DishCreateDTO createDTO) {
        
        User currentUser = getCurrentMerchant();
        log.info("商家 {} 正在为窗口 {} 添加新菜品: {}", currentUser.getUsername(), windowId, createDTO.getName());
        Dish newDish = dishService.createDish(windowId, currentUser.getId(), createDTO);
        
        Map<String, Long> responseData = Collections.singletonMap("dishId", newDish.getId());
        Result<Map<String, Long>> result = Result.success(201, "菜品添加成功，等待审核", responseData);
        
        return new ResponseEntity<>(result, HttpStatus.CREATED);
    }

    @PutMapping("/dishes/{dishId}")
    public ResponseEntity<Result<Void>> updateDish(
            @PathVariable Long dishId,
            @RequestBody DishUpdateDTO updateDTO) {
        
        User currentUser = getCurrentMerchant();
        log.info("商家 {} 正在更新菜品 {}", currentUser.getUsername(), dishId);
        dishService.updateDishByMerchant(dishId, currentUser.getId(), updateDTO);
        
        return new ResponseEntity<>(Result.success(200, "菜品信息更新成功，等待审核", null), HttpStatus.OK);
    }

    @DeleteMapping("/dishes/{dishId}")
    public ResponseEntity<Void> deleteDish(@PathVariable Long dishId) {
        User currentUser = getCurrentMerchant();
        log.info("商家 {} 正在删除菜品 {}", currentUser.getUsername(), dishId);
        dishService.deleteDishByMerchant(dishId, currentUser.getId());
        
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }



    @GetMapping("/windows/{windowId}/statistics")
    public ResponseEntity<Result<MerchantStatisticsVO>> getMerchantStatistics(@PathVariable Long windowId) {
        User currentUser = getCurrentMerchant();
        log.info("商家 {} 正在获取窗口 {} 的统计数据", currentUser.getUsername(), windowId);
        
        MerchantStatisticsVO statistics = statisticsService.getMerchantStatistics(windowId, currentUser.getId());
        Result<MerchantStatisticsVO> result = Result.success(200, "获取本店统计数据成功", statistics);
        
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
} 